package com.example.module.iot.emq.config;

import com.example.module.iot.emq.callback.EmqxCallback;
import com.example.module.iot.emq.util.EmqxUtils;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableConfigurationProperties(EclipsePahoMqttProperties.class)
public class EclipsePahoMqttConfiguration {

    @Bean
    public MqttCallback mqttCallback() {
        return new EmqxCallback();
    }

    @Bean(destroyMethod = "close")
    public MqttClient mqttClient(EclipsePahoMqttProperties eclipsePahoMqttProperties) throws MqttException {
        MqttClient mqttClient = new MqttClient(eclipsePahoMqttProperties.getServerURI(), eclipsePahoMqttProperties.getClientId(), new MemoryPersistence());
        // 连接参数
        MqttConnectOptions options = new MqttConnectOptions();
        // 设置用户名和密码
        options.setUserName(eclipsePahoMqttProperties.getUserName());
        options.setPassword(eclipsePahoMqttProperties.getPassword().toCharArray());
        options.setConnectionTimeout(60);
        options.setKeepAliveInterval(60);
        mqttClient.setCallback(mqttCallback());
        // 连接
        mqttClient.connect(options);
        mqttClient.subscribe(eclipsePahoMqttProperties.getSubscribeTopic());
        return mqttClient;
    }

    @Bean
    public EmqxUtils emqxUtils() {
        return new EmqxUtils();
    }

}
